<template>
  <view>
    <!-- 考虑非APP端长列表和复杂的DOM使用scroll-view会卡顿，所以漂浮顶部选项卡使用page本身的滑动 -->
    <view class="order-list">
      <!-- 下拉刷新 -->
      <view class="refresh-tip" v-if="isRefreshing">
        <text>正在刷新...</text>
      </view>
      <view class="list">
        <view class="onorder" v-if="list.length == 0">
          <image src="../../static/img/noorder.png"></image>
          <view class="text"> 没有相关订单 </view>
        </view>
        <view class="row" v-for="(row, index) in list" :key="index">
          <view class="order-header">
            <view class="type">{{ getStatusText(row.status) }}</view>
            <view class="order-time">{{ formatOrderTime(row.orderTime) }}</view>
          </view>
          <view
            class="order-info"
            @tap="goOrderDetail(row)"
            v-for="(item, idx) in row.orderItems"
            :key="idx"
          >
            <view class="left">
              <image :src="getProductImage(item)"></image>
            </view>
            <view class="right">
              <view class="name">{{ getProductName(item) }}</view>
              <view class="price-number">
                ￥{{ item.pPrice || "0.00" }} x
                {{ item.pNumber || "0" }}
              </view>
            </view>
          </view>
          <view class="detail">
            <view class="number"
              >共{{ getTotalItems(row.orderItems) }}件商品</view
            >
            <view class="sum"
              >合计￥<view class="price">{{ row.orderPrice }}</view>
            </view>
            <view class="nominal">(含运费 ￥0.00)</view>
          </view>
          <view class="btns">
            <!-- 待处理 -->
            <block v-if="row.status == 'PENDING'">
              <view class="default" @tap="conformOrderFun(row, 'CONFIRMED')"
                >确认报价</view
              >
              <view class="default" @tap="conformOrderFun(row, 'CANCELLED')"
                >拒绝报价</view
              >
            </block>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import {
  getOrderList,
  cancelOrder,
  confirmReceive,
  applyRefund,
} from "../../common/api/orderList.js";
import { conformOrder } from "@/common/api/product.js";
import { BASE_URL } from "@/common/utils/request.js";
export default {
  // 页面配置
  onPullDownRefresh: true,
  data() {
    return {
      BASE_URL,
      headerPosition: "fixed",
      headerTop: "0px",
      statusText: {
        // 后端实际状态枚举
        PENDING_SHIP: "待发货",
        SHIPPED: "已发货",
        PENDING_PAYMENT: "待付款",
        COMPLETED: "已完成",
        RETURN_REQUESTED: "退货申请中",
        RETURN_APPROVED: "退货已同意",
        RETURN_REJECTED: "退货被拒绝",
        RETURNED: "已退货",
        CANCELLED: "已取消",
        // 兼容旧键（如果还有使用）

        REFUNDING: "商品退货处理中",
        PENDING: "待确认",
        QUOTED: "已报价",
        CONFIRMED: "已确认",
      },
      orderType: ["全部", "待发货", "待收货", "退换货"],
      orderList: [],
      list: [],
      tabbarIndex: 0,
      isRefreshing: false,
      isCancelling: false,
      addressId: "",
      recinfo: {},
    };
  },
  onLoad(option) {
    //option为object类型，会序列化上个页面传递的参数
    let incomingIndex = Number(option.tbIndex);
    if (Number.isNaN(incomingIndex)) incomingIndex = 0;
    this.tabbarIndex = Math.min(4, Math.max(0, incomingIndex));
    this.loadOrderList();
    //兼容H5下排序栏位置
    // #ifdef H5
    let Timer = setInterval(() => {
      let uniHead = document.getElementsByTagName("uni-page-head");
      if (uniHead.length > 0) {
        this.headerTop = uniHead[0].offsetHeight + "px";
        clearInterval(Timer); //清除定时器
      }
    }, 1);
    // #endif
  },
  onPageScroll(e) {
    return;
    //兼容iOS端下拉时顶部漂移
    this.headerPosition = e.scrollTop >= 0 ? "fixed" : "absolute";
  },
  onShow() {
    uni.getStorage({
      key: "selectAddress",
      success: (e) => {
        this.recinfo = e.data;
        this.addressId = e.data.id;
        if (this.addressId) {
          this.conformOrderFun();
        }
      },
    });
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.refreshOrderList();
  },
  methods: {
    // 检查网络连接
    checkNetwork() {
      return new Promise((resolve) => {
        uni.getNetworkType({
          success: (res) => {
            if (res.networkType === "none") {
              uni.showToast({
                title: "请检查网络连接",
                icon: "none",
              });
              resolve(false);
            } else {
              resolve(true);
            }
          },
          fail: () => {
            resolve(false);
          },
        });
      });
    },

    // 加载订单列表
    async loadOrderList() {
      // 检查网络连接
      const isConnected = await this.checkNetwork();
      if (!isConnected) {
        this.loadTestData();
        return;
      }

      try {
        uni.showLoading({
          title: "加载中...",
        });

        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.showToast({ title: "请先登录", icon: "none" });
          uni.navigateTo({ url: "../login/pre-login" });
          return;
        }

        const response = await getOrderList({
          customerId,
          pageNum: 1,
          pageSize: 50,
          orderType: "custom",
        });

        let ordersData = null;
        // 兼容两种响应结构：{ list, total, ... } 或 { data: { list, total, ... } }
        if (response && Array.isArray(response.list)) {
          ordersData = response.list;
        } else if (
          response &&
          response.data &&
          Array.isArray(response.data.list)
        ) {
          ordersData = response.data.list;
        }
        this.orderList = this.groupOrdersByStatus(ordersData);
        this.showType(this.tabbarIndex);
      } catch (error) {
        this.handleApiError(error, "加载订单列表");
      } finally {
        uni.hideLoading();
      }
    },

    // 刷新订单列表
    async refreshOrderList() {
      // 检查网络连接
      const isConnected = await this.checkNetwork();
      if (!isConnected) {
        uni.stopPullDownRefresh();
        return;
      }

      this.isRefreshing = true;
      try {
        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.stopPullDownRefresh();
          uni.showToast({ title: "请先登录", icon: "none" });
          return;
        }

        const response = await getOrderList({
          customerId,
          pageNum: 1,
          pageSize: 50,
        });
        // 使用相同的数据提取逻辑（兼容两种结构）
        let ordersData = null;
        if (response && Array.isArray(response.list)) {
          ordersData = response.list;
        } else if (
          response &&
          response.data &&
          Array.isArray(response.data.list)
        ) {
          ordersData = response.data.list;
        }
        if (Array.isArray(ordersData) && ordersData.length > 0) {
          this.orderList = this.groupOrdersByStatus(ordersData);
          this.showType(this.tabbarIndex);
          uni.showToast({
            title: "刷新成功",
            icon: "success",
          });
        }
      } catch (error) {
        this.handleApiError(error, "刷新订单列表");
      } finally {
        this.isRefreshing = false;
        uni.stopPullDownRefresh();
      }
    },

    // 按状态分组订单
    groupOrdersByStatus(orders) {
      const grouped = {
        0: [], // 全部
        2: [], // 待发货
        3: [], // 待收货
        4: [], // 退换货
      };

      // 检查orders是否为数组
      if (!orders || !Array.isArray(orders)) {
        return grouped;
      }
      orders.forEach((order) => {
        // 全部订单
        grouped[0].push(order);

        // 按状态分组（根据后端实际状态枚举）
        switch (order.status) {
          // case "PENDING_SHIP": // 等待商家发货 - 待发货
          //   grouped[1].push(order);
          //   break;
          case "SHIPPED": // 商家已发货 - 待收货
            grouped[2].push(order);
            break;
          case "RETURN_REQUESTED": // 退货申请中
          case "RETURN_APPROVED": // 退货已同意
          case "RETURN_REJECTED": // 退货被拒绝
          case "RETURNED": // 已退货
            grouped[3].push(order);
            break;
          case "COMPLETED": // 交易已完成
          case "CANCELLED": // 订单已取消
            // 仅保留在"全部"
            break;
          default:
            // 未知状态也放入全部订单
            break;
        }
      });

      return grouped;
    },

    // 获取状态文本
    getStatusText(status) {
      return this.statusText[status] || "未知状态";
    },

    // 计算总商品数量
    getTotalItems(orderItems) {
      if (!orderItems || !Array.isArray(orderItems)) return 0;
      return orderItems.reduce((total, item) => {
        return total + (parseInt(item.pNumber) || 0);
      }, 0);
    },

    // 格式化订单时间
    formatOrderTime(orderTime) {
      if (!orderTime) return "";
      const date = new Date(orderTime);
      const now = new Date();
      const diff = now - date;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));

      if (days === 0) {
        return (
          "今天 " +
          date.toLocaleTimeString("zh-CN", {
            hour: "2-digit",
            minute: "2-digit",
          })
        );
      } else if (days === 1) {
        return (
          "昨天 " +
          date.toLocaleTimeString("zh-CN", {
            hour: "2-digit",
            minute: "2-digit",
          })
        );
      } else if (days < 7) {
        return `${days}天前`;
      } else {
        return date.toLocaleDateString("zh-CN");
      }
    },

    showType(tbIndex) {
      this.tabbarIndex = tbIndex;
      this.list = this.orderList[tbIndex] || [];
    },

    cancelOrder(row) {
      uni.showModal({
        title: "取消订单",
        editable: true,
        placeholderText: "请输入取消原因（可选）",
        success: (res) => {
          if (res.confirm) {
            this.doCancelOrder(row.id, res.content || "");
          }
        },
      });
    },

    async doCancelOrder(orderId, reason = "") {
      if (this.isCancelling) return;
      this.isCancelling = true;
      try {
        uni.showLoading({ title: "取消订单中..." });
        await cancelOrder(orderId, reason);
        await this.refreshOrderList();
        uni.showToast({ title: "订单已取消", icon: "success" });
      } catch (error) {
        this.handleApiError(error, "取消订单");
      } finally {
        this.isCancelling = false;
        uni.hideLoading();
      }
    },

    async confirmReceive(row) {
      uni.showModal({
        title: "确认收货",
        content: "确认已收到商品？",
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({
                title: "确认收货中...",
              });

              await confirmReceive(row.id);

              // 更新订单状态为已完成
              this.updateOrderStatus(row.id, "COMPLETED");
              this.refreshOrderList();

              uni.showToast({
                title: "确认收货成功",
                icon: "success",
              });
            } catch (error) {
              this.handleApiError(error, "确认收货");
            } finally {
              uni.hideLoading();
            }
          }
        },
      });
    },

    returnGoods(row) {
      uni.showModal({
        title: "申请退货",
        // content: '确定要申请退货吗？',
        editable: true,
        placeholderText: "请输入退货原因",
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({
                title: "申请退货中...",
              });

              await applyRefund(row.id, res.content || "用户申请退货");

              // 更新订单状态为申请退货
              this.updateOrderStatus(row.id, "RETURN_REQUESTED");
              this.refreshOrderList();

              uni.showToast({
                title: "退货申请已提交",
                icon: "success",
              });
            } catch (error) {
              this.handleApiError(error, "申请退货");
            } finally {
              uni.hideLoading();
            }
          }
        },
      });
    },

    async conformOrderFun(row, status) {
      try {
        const customerId = (uni.getStorageSync("userInfo") || {}).id;
        if (!customerId) {
          uni.showToast({ title: "请先登录", icon: "none" });
          uni.navigateTo({ url: "../login/pre-login" });
          return;
        }
        // if (
        //   !row ||
        //   !Array.isArray(row.orderItems) ||
        //   row.orderItems.length === 0
        // ) {
        //   uni.showToast({ title: "该订单没有可购买的商品", icon: "none" });
        //   return;
        // }
        uni.showLoading({ title: "处理中..." });
        if (status == "CONFIRMED") {
          // 确认报价
          if (!this.addressId) {
            uni.showModal({
              title: "操作确认",
              content: "同意之前请先选择您的地址，以便供应商为您发货",
              success: function (res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: "../user/address/address?type=select",
                  });
                } else if (res.cancel) {
                  return;
                }
              },
            });
          } else {
            const params = {
              customerId,
              status,
              id: row.productRequirementId,
              addressId: this.addressId,
            };
            const res = await conformOrder(params);
            if (res.data.ok) {
              uni.showToast({ title: res.data.message, icon: "success" });
              this.refreshOrderList();
            } else {
              uni.showToast({ title: res.data.message, icon: "none" });
            }
          }
        } else {
          // 拒绝报价
          const params = {
            customerId,
            status,
            id: row.productRequirementId,
            addressId: "",
          };
          const res = await conformOrder(params);
          if (res.data.ok) {
            uni.showToast({ title: res.data.message, icon: "success" });
            this.refreshOrderList();
          } else {
            uni.showToast({ title: res.data.message, icon: "none" });
          }
        }
      } catch (error) {
        this.handleApiError(error, "再次购买");
      } finally {
        uni.hideLoading();
      }
    },
    // 跳转到产品详情
    async toProductDetail(row) {
      try {
        uni.showLoading({ title: "加载中..." });
        const res = await getProductById(row.productId);
        if (res.data.ok) {
          uni.navigateTo({
            url: `/pages/product/detail?id=${row.productId}&name=${row.productName}`,
          });
        } else {
          uni.showToast({ title: res.data.msg, icon: "none" });
        }
        uni.showToast({ title: "已加入确认订单", icon: "success" });

        // 跳转到确认订单页面（非tab页，用 navigateTo）
        setTimeout(() => {
          uni.navigateTo({ url: "/pages/order/confirmation?productFlag=true" });
        }, 500);
      } catch (error) {
        this.handleApiError(error, "再次购买");
      } finally {
        uni.hideLoading();
      }
    },

    viewRefundProgress(row) {
      uni.navigateTo({
        url: `/pages/user/order_detail/order_detail?id=${row.id}`,
      });
    },

    updateOrderStatus(orderId, newStatus) {
      const keys = Object.keys(this.orderList || {});
      for (const key of keys) {
        const group = this.orderList[key];
        if (Array.isArray(group) && group.length > 0) {
          for (let j = 0; j < group.length; j++) {
            if (group[j].id == orderId) {
              group[j].status = newStatus;
              this.showType(this.tabbarIndex);
              return;
            }
          }
        }
      }
    },

    // 跳转到订单详情
    goOrderDetail(row) {
      if (!row || !row.id) {
        uni.showToast({
          title: "订单数据无效",
          icon: "none",
        });
        return;
      }
      uni.navigateTo({
        url: `/pages/user/order_detail/order_detail?id=${row.id}`,
      });
    },

    // 获取商品名称
    getProductName(row) {
      return row.product.pName;
    },

    // 获取商品图片
    getProductImage(item) {
      return (
        (item.product.pImgUrl &&
          `${BASE_URL}${item.product.pImgUrl.split(",")[0]}`) ||
        "/static/img/noorder.png"
      );
    },

    // 处理API错误
    handleApiError(error, operation) {
      uni.showToast({
        title: `${operation}失败`,
        icon: "none",
      });
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f3f3f3;
}

.topTabBar {
  width: 100%;
  position: fixed;
  top: 0;
  z-index: 10;
  background-color: #f8f8f8;
  height: 80upx;
  display: flex;
  justify-content: space-around;

  .grid {
    width: 20%;
    height: 80upx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #444;
    font-size: 28upx;

    .text {
      height: 76upx;
      display: flex;
      align-items: center;

      &.on {
        color: #f06c7a;
        border-bottom: solid 4upx #f06c7a;
      }
    }
  }
}

.order-list {
  margin-top: 80upx;
  padding-top: 20upx;
  width: 100%;

  .debug-btn {
    width: 94%;
    margin: 0 auto 20upx;
    height: 80upx;
    background-color: #007aff;
    border-radius: 10upx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 28upx;
  }

  .refresh-tip {
    width: 100%;
    height: 60upx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f8f8f8;
    font-size: 24upx;
    color: #666;
  }

  .order-info {
    display: flex;
    padding: 10px;
    border-bottom: 1px solid #f1f1f1;
    /* 添加底部边框 */
  }

  .order-info:last-child {
    border-bottom: none;
    /* 去掉最后一个商品项的边框 */
  }

  .list {
    width: 94%;
    margin: 0 auto;

    .onorder {
      width: 100%;
      height: 50vw;
      display: flex;
      justify-content: center;
      align-content: center;
      flex-wrap: wrap;

      image {
        width: 20vw;
        height: 20vw;
        border-radius: 100%;
      }

      .text {
        width: 100%;
        height: 60upx;
        font-size: 28upx;
        color: #444;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .row {
      width: calc(100% - 40upx);
      padding: 10upx 20upx;
      border-radius: 10upx;
      background-color: #fff;
      margin-bottom: 20upx;

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 50upx;
        margin-bottom: 10upx;

        .type {
          font-size: 26upx;
          color: #ec652f;
        }

        .order-time {
          font-size: 22upx;
          color: #999;
        }
      }

      .order-info {
        width: 100%;
        display: flex;

        .left {
          flex-shrink: 0;
          width: 25vw;
          height: 25vw;

          image {
            width: 25vw;
            height: 25vw;
            border-radius: 10upx;
          }
        }

        .right {
          width: 100%;
          margin-left: 10upx;
          position: relative;

          .name {
            width: 100%;
            font-size: 28upx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
          }

          .spec {
            color: #a7a7a7;
            font-size: 22upx;
          }

          .price-number {
            position: absolute;
            bottom: 0;
            width: 100%;
            display: flex;
            justify-content: flex-end;
            font-size: 22upx;
            color: #333;
            display: flex;
            align-items: flex-end;
            right: 20upx;
          }
        }
      }

      .detail {
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        height: 60upx;
        font-size: 26upx;

        .sum {
          padding: 0 8upx;
          display: flex;
          align-items: flex-end;

          .price {
            font-size: 30upx;
          }
        }
      }

      .btns {
        height: 80upx;
        display: flex;
        align-items: center;
        justify-content: flex-end;

        view {
          min-width: 120upx;
          height: 50upx;
          padding: 0 20upx;
          border-radius: 50upx;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 28upx;
          margin-left: 20upx;
        }

        .default {
          border: solid 1upx #ccc;
          color: #666;
        }

        .pay {
          border: solid 1upx #ec652f;
          color: #ec652f;
        }
      }
    }
  }
}
</style>
